#!/usr/local/bin/python
# -*- coding: utf-8 -*-


from datetime import datetime
from dateutil.relativedelta import relativedelta


from PyQt5.QtWidgets import QWidget, QAbstractItemView, QTableWidgetItem
from PyQt5 import QtWidgets
from xToolkit.xstring import xstring

import init
import initLogger
import initAccountBookPage


import toolkit
from AccountBook import AccountBook

from ui.AccountBookUI_relative_layout_c import Ui_AccountBook


class AccountBookWidget(QWidget, Ui_AccountBook):
    def __init__(self):
        super(AccountBookWidget, self).__init__()
        self.setupUi(self)

        self.currentDate = datetime.now()  #记录当前事件
        self.targetDate = self.currentDate  - relativedelta(days=init.GO_DAYS)#记录当前系统查看数据的时间

        self.initAccountBook()


    def initAccountBook(self):
        '''
        函数功能：初始化账簿页面
        :return:
        '''
        initLogger.logger.debug("call initAccountBookUI")
        self.initAccountBookUI()
        self.initAccountBookTableUI()
        self.initAccountBookTableData()

    def initAccountBookUI(self):
        '''
        函数功能：对记账簿的UI进行初始化
        :return:
        '''
        #初始化标题
        self.initAccountBookTitleUI()

        #初始化查询模块相关控件
        self.year_comboBox.addItems(init.YEAR_NAME_LIST)
        self.month_comboBox.addItems(init.MONTH_NAME_LIST)
        self.year_comboBox.setCurrentText(str(self.targetDate.year))
        self.month_comboBox.setCurrentText(str(self.targetDate.month))
    def initAccountBookTitleUI(self):
        accountBookTitleStr="%d年%d月账簿"%(self.targetDate.year, self.targetDate.month)
        self.title_label.setText(accountBookTitleStr)
    def initAccountBookTableUI(self):
        '''
        函数功能：初始化账簿表UI
        :return:
        '''
        self.account_book_tableWidget.setRowCount(initAccountBookPage.ACCOUNT_BOOK_TABLE_ROW_COUNT)  # 设置行数目
        self.account_book_tableWidget.setColumnCount(initAccountBookPage.ACCOUNT_BOOK_TABLE_COLUMN_COUNT)  # 设置列数目
        self.account_book_tableWidget.setHorizontalHeaderLabels(initAccountBookPage.ACCOUNT_BOOK_TABLE_COLUMN_CONTEXT)

        self.account_book_tableWidget.resizeRowsToContents()  # 设置行宽自适应
        self.account_book_tableWidget.resizeColumnsToContents()  # 设置列宽自适应
        self.account_book_tableWidget.setShowGrid(True)  # 设置显示网络线
        self.account_book_tableWidget.setAlternatingRowColors(True)  # 设置表格颜色交错显示
        self.account_book_tableWidget.verticalHeader().setVisible(False)  # 隐藏垂直标题
        self.account_book_tableWidget.horizontalHeader().setStretchLastSection(True)  # 设置最后一列自动填充容

        self.account_book_tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置选中整行
        self.account_book_tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)  # 禁止编辑单元格

    def initAccountBookTableData(self):
        '''
        函数功能：初始化账簿表数据
        :return:
        '''

        accountBook = AccountBook()
        accountBookResult = accountBook.getAccountBookDataMonthly(self.targetDate.year, self.targetDate.month)

        accountBooklen = len(accountBookResult)
        self.account_book_tableWidget.setRowCount(accountBooklen)  #根据实际数据量设置表格行数
        for i in range(len(accountBookResult)):

            dataRow = accountBookResult[i]

            subjectNameStr_0 = "%s\t" % (dataRow.subject_name_0)
            subjectWidgetItem_0 = QTableWidgetItem(subjectNameStr_0)
            self.account_book_tableWidget.setItem(i, 0, subjectWidgetItem_0)

            subjectNameStr_1 = "%s\t" % (dataRow.subject_name_1)
            subjectWidgetItem_1 = QTableWidgetItem(subjectNameStr_1)
            self.account_book_tableWidget.setItem(i, 1, subjectWidgetItem_1)

            subjectNameStr_2 = "%s\t" % (dataRow.subject_name_2)
            subjectWidgetItem_2 = QTableWidgetItem(subjectNameStr_2)
            self.account_book_tableWidget.setItem(i, 2, subjectWidgetItem_2)

            subjectNameStr_3 = "%s\t\t" % (dataRow.subject_name_3)
            subjectWidgetItem_3 = QTableWidgetItem(subjectNameStr_3)
            self.account_book_tableWidget.setItem(i, 3, subjectWidgetItem_3)

            subjectNameStr_4 = "%s\t" % (dataRow.subject_name_4)
            subjectWidgetItem_4 = QTableWidgetItem(subjectNameStr_4)
            self.account_book_tableWidget.setItem(i, 4, subjectWidgetItem_4)

            subjectNameStr_5 = "%s\t" % (dataRow.subject_name_5)
            subjectWidgetItem_5 = QTableWidgetItem(subjectNameStr_5)
            self.account_book_tableWidget.setItem(i, 5, subjectWidgetItem_5)


            startValueStr=xstring.dispose(toolkit.processValueSignificant(dataRow.start_value)).humanized_amount(complex=True)
            startValueWidgetItem = QTableWidgetItem(startValueStr)
            self.account_book_tableWidget.setItem(i, 6, startValueWidgetItem)


            increaseValueStr = xstring.dispose(toolkit.processValueSignificant(dataRow.increase_value)).humanized_amount(complex=True)
            increaseValueWidgetItem = QTableWidgetItem(increaseValueStr)
            self.account_book_tableWidget.setItem(i, 7, increaseValueWidgetItem)


            decreaseValueStr = xstring.dispose(toolkit.processValueSignificant(dataRow.decrease_value)).humanized_amount(complex=True)
            decreaseValueWidgetItem = QTableWidgetItem(decreaseValueStr)
            self.account_book_tableWidget.setItem(i, 8, decreaseValueWidgetItem)

            endValueStr = xstring.dispose(toolkit.processValueSignificant(dataRow.end_value)).humanized_amount(complex=True)
            endValueWidgetItem = QTableWidgetItem(endValueStr)
            self.account_book_tableWidget.setItem(i, 9, endValueWidgetItem)

            differentValue = dataRow.end_value - dataRow.start_value
            differentValueStr = xstring.dispose(toolkit.processValueSignificant(differentValue)).humanized_amount(complex=True)
            differentValueWidgetItem = QTableWidgetItem(differentValueStr)
            self.account_book_tableWidget.setItem(i, 10, differentValueWidgetItem)

        #根据实际数据情况，设置行列的自适应。
        self.account_book_tableWidget.resizeRowsToContents()  # 设置行宽自适应
        self.account_book_tableWidget.resizeColumnsToContents()  # 设置列宽自适应


    def clearAccountBookTableContext(self):
        '''
        对记账凭证中表格中的内容进行清空
        :return:
        '''
        self.account_book_tableWidget.clear()
        self.account_book_tableWidget.setHorizontalHeaderLabels(initAccountBookPage.ACCOUNT_BOOK_TABLE_COLUMN_CONTEXT)
        self.initAccountBookTitleUI()

    def onSearch(self):
        '''
        函数功能：响应记账簿查询按钮事件
        :return:
        '''

        year = int(self.year_comboBox.currentText())
        month = int(self.month_comboBox.currentText())
        self.targetDate = toolkit.setTargetDate(year, month)

        self.clearAccountBookTableContext()

        self.initAccountBookTitleUI()  # 设置记账凭证标题
        self.initAccountBookTableUI()
        self.initAccountBookTableData()

    def onGoLastMonth(self):
        """
        函数功能；展示上一个月的账簿数据
        :return:
        """

        self.targetDate = toolkit.getLastMonth(self.targetDate, number=1)
        initLogger.logger.debug("target year: %d   month: %d" % (self.targetDate.year, self.targetDate.month))

        self.clearAccountBookTableContext()

        self.year_comboBox.setCurrentText(str(self.targetDate.year))
        self.month_comboBox.setCurrentText(str(self.targetDate.month))

        self.initAccountBookTitleUI()  # 设置记账凭证标题
        self.initAccountBookTableUI()
        self.initAccountBookTableData()


    def onGoNextMonth(self):
        """
        函数功能；展示下一个月的账簿数据
        :return:
        """

        self.targetDate = toolkit.getNextMonth(self.targetDate, number=1)
        initLogger.logger.debug("target year: %d   month: %d" % (self.targetDate.year, self.targetDate.month))
        self.clearAccountBookTableContext()

        self.year_comboBox.setCurrentText(str(self.targetDate.year))
        self.month_comboBox.setCurrentText(str(self.targetDate.month))

        self.initAccountBookTitleUI()  # 设置记账凭证标题
        self.initAccountBookTableUI()
        self.initAccountBookTableData()

    def onUpdateAccountBook(self):
        '''
        函数功能：更新记账簿数据
        :return:
        '''
        accountBook = AccountBook(self.targetDate.year, self.targetDate.month)
        accountBook.getInitAccountBookValue()
        accountBook.calculateAccountVoucherMonthly()
        accountBook.genAccountBook()

        self.clearAccountBookTableContext()
        self.initAccountBookTableUI()
        self.initAccountBookTableData()


    def onUpdateAllYearAccountBook(self):
        '''
        函数功能：更新全年记账簿数据
        :return:
        '''
        pass